package com.ex.common;

import java.util.concurrent.ConcurrentLinkedQueue;

public class ObjectPool<T> {
	private ObjectFactory<T> factory;

	private ConcurrentLinkedQueue<T> queue = new ConcurrentLinkedQueue<T>();

	public ObjectPool(ObjectFactory<T> factory, int initSize, int maxSize) {
		this.factory = factory;
		for (int i = 0; i < initSize; i++) {
			queue.add(factory.newInstance());
		}
	}

	public T alloc() {
		T t=queue.poll();
		if (t==null) {
			t=factory.newInstance();
		}
		return t;
	}

	public void free(T t) {
		queue.add(t);
	}

}
